package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;  
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.android.ChartPanel;
import com.java4less.rchart.gc.android.ChartAndroidImage;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;

public class WaterStationChartActivity extends Activity {
	private static final int MENU_LIST = Menu.FIRST+1;
	private static final int MENU_LEGEND = Menu.FIRST+2;
	private Map<String,String> station = new HashMap<String,String>();
	private Map<String,String> datakeys = new HashMap<String,String>();
	private Map<String,List<Map<String, String>>> datalst = new HashMap<String,List<Map<String, String>>>();
	
	private ChartLoader cha = new ChartLoader();
	private ChartPanel chartPanel;
	private String code;
	private String type;
	private ProgressDialog dialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.water_chart);   //软件activity的布局
		ActivityStackControlUtil.add(this);	
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		initComponent();
	}

	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					ChartAndroidImage.assets = getAssets();
					String chartfile = "waterchart.txt";
					chartPanel = new ChartPanel(getApplicationContext());
					try {
						chartPanel.setChart(loadFromAsset(chartfile));
					} catch (Exception e) {
						Log.e(ChartPanel.TAG, "Could not lod chart from file.", e);
					}
					LinearLayout layout = (LinearLayout)findViewById(R.id.pnlMiddle);
					layout.addView(chartPanel);
					//
					TextView lblTitle = (TextView)findViewById(R.id.lblTitle);
					lblTitle.setText(station.get("name"));
					TextView lblStationCode = (TextView)findViewById(R.id.lblStationCode);
					lblStationCode.setText(station.get("code"));
					TextView lblStationRiver = (TextView)findViewById(R.id.lblStationRiver);
					lblStationRiver.setText(station.get("river"));
					TextView lblStationAddr = (TextView)findViewById(R.id.lblStationAddr);
					lblStationAddr.setText(station.get("addr"));
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadWaterData();	
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}

	private void downloadWaterData() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new WaterDataHandler());
		} catch (Exception e) {
			dialog.cancel();
			throw new InternetException("");
		}	
	}
	
	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		code = intent.getStringExtra("code");
		type = intent.getStringExtra("type");
		String server = CommConstant.Sever.WATER_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"waterchart.xml");
		} else {
			URL url = new URL(server + "water/WaterHistory.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&stacode=" + code + "&type=" + CommConstant.Water.WATER_OVER);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class WaterDataHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("station".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					station.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			}else if ("day".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					datakeys.put(attrs.getValue(i), attrs.getLocalName(i));
				}
			}else if ("water".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				String key = data.get("time").split(" ")[0];
				if (datalst.containsKey(key)) {
					datalst.get(key).add(data);
				} else {
					List<Map<String,String>> list  = new ArrayList<Map<String,String>>();
					list.add(data);
					datalst.put(key, list);
				}
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
		
	public Chart loadFromAsset(String name) throws IOException {
		InputStream is = getAssets().open(name);
		cha.loadFromFile(is, true);
		StringBuffer labels = new StringBuffer();
		StringBuffer values1 = new StringBuffer();
		StringBuffer values2 = new StringBuffer();
		StringBuffer values3 = new StringBuffer();
		StringBuffer values4 = new StringBuffer();
		
		String jjx = station.get("jjx");
		
		//循环数据
		for(Iterator<Entry<String,String>> iterator = datakeys.entrySet().iterator(); iterator.hasNext();) {
			Entry<String,String> entry = iterator.next();
			List<Map<String, String>> lst = datalst.get(entry.getKey());
			Map<String,String> data = lst.get(0);
			labels.append(entry.getKey().substring(5) + "|");
			values1.append(data.get("value") + "|");
			values2.append(data.get("Q") + "|");
			values3.append(data.get("OQ") + "|");
			if (!CommConstant.Water.DEFAULT_OVER.equals(jjx)) {
				values4.append(jjx + "|");
			}
		}
		//设置报表参数
		cha.setParameter("XAXIS_LABELS", labels.substring(0,labels.length()-1));
		cha.setParameter("SERIE_DATA_1", values1.substring(0,values1.length()-1));
		cha.setParameter("SERIE_DATA_2", values2.substring(0,values2.length()-1));
		cha.setParameter("SERIE_DATA_3", values3.substring(0,values3.length()-1));
		if (!CommConstant.Water.DEFAULT_OVER.equals(jjx)) {
			cha.setParameter("SERIE_DATA_4", values4.substring(0,values4.length()-1));
		}
		//
		Chart c = cha.build(false, false);
		c.setWidth(LayoutParams.FILL_PARENT);
		c.setHeight(LayoutParams.FILL_PARENT);
		return c;
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_LIST, 1, R.string.menu_list);
		menu.add(0, MENU_LEGEND, 2, R.string.menu_legend);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		intent.putExtra("code", code);
		intent.putExtra("type", type);
		switch (item.getItemId()) {
			case MENU_LIST:
				intent.setClass(getApplicationContext(), WaterStationDataActivity.class);
				startActivity(intent);
				return true;
			case MENU_LEGEND:
				intent.setClass(getApplicationContext(), WaterStationLegendActivity.class);
				startActivity(intent);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}